<template>
	<jk-dialog
		v-model="showDialog"
		:title="`选择-${title}`"
		width="1000px"
		append-to-body
		@on-visible-change="onVisibleChange"
		@on-cancel="onVisibleChange(false)"
		@on-confirm="onConfirmBtn"
	>
		<header ref="box1" class="flex-end-center-wrap">
			<div class="flex-start-center margin-bottom-10">
				<jk-date-picker v-model="searchParams.belongDate" :disabled-future-time="true" size="small" type="daterange" style="width: 280px; margin: 0 5px" value-format="yyyy-MM-dd" placeholder="选择日期" class="search-bar-item-size1 item-gap"></jk-date-picker>
				<el-select v-model="searchParams.typeId" disabled size="small" style="width: 100px;" placeholder="检验类型" class="width-100-percent margin-right-6" @change="onWorkshopChange">
					<el-option
						v-for="item in examineList"
						:key="item.id"
						:value="item.id"
						:label="item.name"
					></el-option>
				</el-select>
				<jk-search-button @click="onSearchBtn"></jk-search-button>
			</div>
		</header>

		<jk-table
			ref="jkTable"
			:radio-config="{trigger: 'row'}"
			:loading="tableLoading"
			class="width-100-percent"
			:data="tableData"
			border
			highlight-hover-row
			highlight-current-row
			:height="tableHeight - 100"
			:checkbox-config="{checkMethod: checkboxMethod}"
			@checkbox-change="onCheckBoxChange"
		>
			<vxe-table-column type="checkbox" width="60" align="center" fixed="left"></vxe-table-column>
			<vxe-table-column field="name" title="品种名称" fixed :min-width="200"> </vxe-table-column>
			<vxe-table-column field="batchCode" title="批号" :min-width="100" />
			<vxe-table-column field="spinTypeName" align="right" title="种类" :min-width="100" />
		</jk-table>
		<footer ref="box2" class="flex-end-center margin-top-10">
			<jk-page
				:page-index="searchParams.pageNo"
				:page-sizes="searchParams.pageSizes"
				:page-size="searchParams.pageSize"
				:total="totalCount"
				layout="total, prev, pager, next"
				@on-change="onPageChange"
			/>
		</footer>
	</jk-dialog>
</template>

<script>
    import calDialogHeight from '../../../../mixins/cal-table-height';
    import { pageConfig } from '../../../../utils/jk/jk-tool';
    import {
        productionPrdNoticeMachineChangeProduceBreedList
    } from '../../../../api/quality/qualityRecord';
    import { systemBusinessDictPage } from '../../../../api/quality/processQuality';
    // 原有的
    // import { productionProcessPrdNoticePage } from '@/api/production/xsNotice';
    // import { noticeStateList } from '../../../../utils/jk/status-option-list';

    export default {
        mixins: [calDialogHeight],
        props: {
            productionList: {
                type: Array,
                default() {
                    return [];
                }
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            checkKeyName: {
                type: String,
                default: 'batchCode'
            },
            title: {
                type: String,
                default: '品种'
            },
            processCode: {
                type: String,
                default: ''
            },
            ruleForm: {
                type: Object,
                default() {
                    return {};
                }
            }
        },
        data() {
            return {
                totalCount: 0,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    beforeDay: null,
                    typeId: null,
                    typeCode: '',
                    belongDate: [],
                    pageSize: pageConfig.pageSize
                },
                tableData: [],
                examineList: [],
                showDialog: false,
                tableLoading: false,
                checkData: []
            };
        },
        methods: {
            onCheckBoxChange({ records }) {
                this.checkData = records.filter(x => !x._disabled).map(x => {
                    return x;
                });
            },
            checkboxMethod({ row }) {
                return row._disabled !== true;
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            onConfirmBtn() {
                if (Object.keys(this.checkData).length) {
                    this.$emit('on-confirm', this.checkData);
                } else {
                    this.$tipsBar(this, 'unChoose');
                }
            },
            // 获取成品半成品
            getTypeListRequest() {
                const params = {
                    categoryCode: 'QUALITY_TYPE',
                    pageSize: 100,
                    pageNo: 1
                };
                return systemBusinessDictPage(params).then(res => {
                    if (res.data.status === 200) {
                        this.examineList = res.data.res || [];
                    }
                });
            },
            async onWorkshopChange(typeId) {
                this.examineList.forEach(x => {
                    if (typeId === x.id) {
                        this.$set(this.searchParams, 'typeName', x.name);
                        this.$set(this.searchParams, 'typeCode', x.code);
                        this.$set(this.searchParams, 'typeId', x.id);
                    }
                });
            },
            async getListRequest() {
                this.tableLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                if (params.typeCode === 'CP_QUALITY') params.processCodeList = ['XS', 'LT'];
                if (params.typeCode === 'BCP_QUALITY') params.processCodeList = ['QH', 'SM', 'BT', 'CS'];
                if (params.belongDate.length > 1) delete params.beforeDay;
                params.startDate = params.belongDate[0];
                params.endDate = params.belongDate[1];
                delete params.belongDate;
                try {
                    const res = await productionPrdNoticeMachineChangeProduceBreedList(params);
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.totalCount = res.data.count;
                        this.tableData = res.data.res;
                        this.setCheckState(res.data.res || []);
                    }
                } catch (error) {
                    this.tableLoading = false;
                }
            },
            setCheckState(arr) {
                arr.forEach((x) => {
                    x._disabled = false;
                    this.productionList.forEach(k => {
                        if (x.batchCode === k[this.checkKeyName]) {
                            x._disabled = true;
                        }
                    });
                });
                this.tableData = arr;
                this.tableData.forEach((x, index) => {
                    if (x._disabled) {
                        this.$refs.jkTable.$refs.xTable.setCheckboxRow([this.tableData[index], this.tableData[index]], true);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                }
            },
            async getDependentData() {
                this.tableLoading = true;
                await this.getTypeListRequest();
                this.$set(this.searchParams, 'typeName', this.ruleForm.typeName);
                this.$set(this.searchParams, 'typeCode', this.ruleForm.typeCode);
                this.$set(this.searchParams, 'typeId', this.ruleForm.typeId);
                if (this.searchParams.belongDate.length < 1) {
                    this.$set(this.searchParams, 'beforeDay', 1);
                }
                await this.getListRequest();
            }

        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
